package com.waa.gulimall.ware.service.impl;

import com.waa.gulimall.common.constant.WareConstant;
import com.waa.gulimall.ware.entity.PurchaseDetailEntity;
import com.waa.gulimall.ware.service.PurchaseDetailService;
import com.waa.gulimall.ware.service.WareSkuService;
import com.waa.gulimall.ware.vo.MergeVo;
import com.waa.gulimall.ware.vo.PurchaseDoneVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.waa.gulimall.common.utils.PageUtils;
import com.waa.gulimall.common.utils.Query;

import com.waa.gulimall.ware.dao.PurchaseDao;
import com.waa.gulimall.ware.entity.PurchaseEntity;
import com.waa.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
@Slf4j
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {


    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private  PurchaseDao purchaseDao;
    @Autowired
    private WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        final QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        String key = (String)params.get("key");
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils unreceiveQueryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", WareConstant.PurchaseStatusEnum.CREATE.getCode()).or().eq("status",WareConstant.PurchaseStatusEnum.ASSIGEND.getCode())
        );
        return new PageUtils(page);
    }


    //合并采购单
    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
         Long purchaseId = mergeVo.getPurchaseId();
        if (null==purchaseId){
            //新建采购单
          PurchaseEntity purchaseEntity = new PurchaseEntity();
          log.info(purchaseEntity.toString());
          purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATE.getCode());
          purchaseDao.insert(purchaseEntity);
          purchaseId = purchaseEntity.getId();
        }
        //合并采购单
        final PurchaseEntity purchaseEntity = this.getById(purchaseId);
        log.info(purchaseEntity.toString());
        if (purchaseEntity.getStatus()==WareConstant.PurchaseStatusEnum.CREATE.getCode()|| //判断采购单的状态
        purchaseEntity.getStatus()==WareConstant.PurchaseStatusEnum.ASSIGEND.getCode()
        ) {
            log.info("进入判断采购单的状态");
            final List<Long> items = mergeVo.getItems();
            final List<PurchaseDetailEntity> collect1 = purchaseDetailService.listByIds(items).stream().map(item -> {
                return item;
            }).filter(s -> {
                return s.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATE.getCode() || s.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGEND.getCode();
            }).collect(Collectors.toList());
            Long finalPurchaseId = purchaseId;
            final List<PurchaseDetailEntity> collect = collect1.stream().map(item -> {
                final PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                purchaseDetailEntity.setId(item.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGEND.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);
        }
    }


    //领取采购单
    @Override
    public void received(List<Long> ids) {
        //只修改是新建或者已分配的状态
        final List<PurchaseEntity> purchaseEntities = this.listByIds(ids);
        final List<PurchaseEntity> collect = purchaseEntities.stream().map(item -> {
            final PurchaseEntity purchaseEntity = new PurchaseEntity();
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATE.getCode() ||
                item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGEND.getCode())
            {
                purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                purchaseEntity.setId(item.getId());
                return purchaseEntity;
            }
            return null;
        }).collect(Collectors.toList()).stream().filter(item->{
            return null!=item;
        }).collect(Collectors.toList());
      //改变采购单的状态
        this.updateBatchById(collect);
     //改变采购项状态
        final List<Long> purchaseDetailIds = collect.stream().map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        final List<PurchaseDetailEntity> detailEntities = purchaseDetailService.list(new QueryWrapper<PurchaseDetailEntity>().in("purchase_id", purchaseDetailIds));
        final List<PurchaseDetailEntity> collect1 = detailEntities.stream().map(item -> {
            final PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item.getId());
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect1);
    }
    @Transactional
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        //改变采购单状态
        final Long purchaseId = purchaseDoneVo.getId();
     log.info("改变采购单状态");
        //改变采购项状态
        AtomicReference<Boolean> flag = new AtomicReference<>(true);
        final List<PurchaseDetailEntity> collect = purchaseDoneVo.getItems().stream().map(item -> {
            final PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASEXCEPTION.getCode()) {
                flag.set(false);

                purchaseDetailEntity.setStatus(item.getStatus());
            }else {
                purchaseDetailEntity.setStatus(item.getStatus());
                //3.将成功采购的进行入库
                final PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.wareHousing(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum());
            }
            purchaseDetailEntity.setId(item.getItemId());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect);
        final PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setStatus(flag.get()?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASEXCEPTION.getCode());
        purchaseEntity.setId(purchaseId);
        purchaseDao.updateById(purchaseEntity);

    }

}